export function downloadFile(url) {
  // 文件下载
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url, // url
      success: res => {
        if (res.statusCode === 200) {
          resolve(res)
        }
        else {
          reject(res)
        }
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

export function saveFile(savePath) {
  // 文件保存
  return new Promise((resolve, reject) => {
    uni.saveFile({
      tempFilePath: savePath,
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

export function delateThisFile(filePath) {
  // 删除某个文件
  return new Promise((resolve, reject) => {
    uni.removeSavedFile({
      tempFilePath: filePath,
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

export function hashCode(string) {
  if (string.length === 0) return ''
  let hash = 0
  let chr
  for (let i = 0; i < string.length; i++) {
    chr = string.charCodeAt(i)
    hash = ((hash << 5) - hash) + chr
    hash |= 0
  }
  return hash.toString().replace('-', 'O')
}

export function getStorage(key, cb) {
  getCache(key, cb)
}

export function setStorage(key, val, cb) {
  setCache(key, val, cb)
}
/* uni app单个key获取多个很慢，所以用一个字段存储所有值加快访问 */
const IMAGE_CACHE_KEY = 'IMAGE_CACHE_KEY'
const imageCacheMap = new Map() // {key1:val1,key2:val2,key3:val3}
let debouncetimer = null

function setCache(key, val, cb) {
  const cacheMapData = imageCacheMap.get(IMAGE_CACHE_KEY)
  if (!cacheMapData || !cacheMapData[key]) {
    const data = {
      [key]: val
    }
    if (!cacheMapData) {
      imageCacheMap.set(IMAGE_CACHE_KEY, data)
    }
    else {
      imageCacheMap.set(IMAGE_CACHE_KEY, Object.assign(cacheMapData, data))
    }
  }
  console.log(cacheMapData.get(IMAGE_CACHE_KEY))
  if (debouncetimer) {
    clearTimeout(debouncetimer)
  }
  /* 延迟批量存储，避免快速进行多次写入 */
  debouncetimer = setTimeout(() => {
    const sT = +new Date()
    // uni.setStorage({
    //  key: IMAGE_CACHE_KEY,
    //  data: imageCacheMap.get(IMAGE_CACHE_KEY),
    //  success: function() {
    //   console.log('setCache---------------------------------' + (+new Date - sT));
    //   console.log(imageCacheMap.get(IMAGE_CACHE_KEY));
    //   cb && cb(val)
    //  },
    //  fail: function() {
    //   cb && cb(null)
    //  }
    // });
  }, 1000)
}

// let isInit = false
// if (!isInit) {
//  try {
//   let sT = +new Date
//   const cacheData = uni.getStorageSync(IMAGE_CACHE_KEY);
//   if (cacheData && Object.keys(cacheData).length > 0) {
//    imageCacheMap.set(IMAGE_CACHE_KEY, cacheData)
//   }
//   console.log('getCache---------------------------------' + (+new Date - sT));
//  } catch (e) {
//   // error
//  }
//  isInit = true
// }

function getCache(key, cb) {
  const cacheMapData = imageCacheMap.get(IMAGE_CACHE_KEY)
  console.log(cacheMapData)
  cb && cb(cacheMapData[key])
  // if (cacheMapData && cacheMapData[key]) {
  //  cb && cb(cacheMapData[key])
  // } else {
  //  cb && cb(null)
  // }
}

// 全局唯一标识符
export function guid(len = 32, firstU = true, radix = null) {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  radix = radix || chars.length

  if (len) {
    // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
    for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
  }
  else {
    let r
    // rfc4122标准要求返回的uuid中,某些位为固定的字符
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    for (let i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16
        uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
  if (firstU) {
    uuid.shift()
    return `u${uuid.join('')}`
  }
  else {
    return uuid.join('')
  }
}
